package com.lykj.modules.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.lykj.common.cache.ParamCache;
import com.lykj.core.boot.ctrl.LykjController;
import com.lykj.core.cache.utils.CacheUtil;
import com.lykj.core.log.exception.ServiceException;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.core.tool.api.R;
import com.lykj.core.tool.utils.Func;
import com.lykj.modules.desk.entity.Notice;
import com.lykj.modules.job.jobhandler.ShsyTaskJob;
import com.lykj.modules.shop.entity.StoreCalendar;
import com.lykj.modules.shop.entity.StoreProduct;
import com.lykj.modules.shop.entity.UserExtract;
import com.lykj.modules.shop.entity.UserOrder;
import com.lykj.modules.shop.service.*;
import com.lykj.modules.shop.znapi.ZnApiUtils;
import com.lykj.modules.system.entity.Param;
import com.lykj.modules.system.service.ParamService;
import com.lykj.modules.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

import static com.lykj.core.cache.constant.CacheConstant.PARAM_CACHE;

/**
 * 商城首页 控制器
 *
 * @author cxl
 * @since 2022-01-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("lykj-shop/store")
@Api(value = "商城首页", tags = "商城首页")
public class IndexController extends LykjController {
	private final StoreProductService storeProductService;
	private final ParamService paramService;
	private final StoreCalendarService storeCalendarService;
	private final UserService userService;
	private final UserOrderService userOrderService;
	private final UserBonusService userBonusService;
	private final UserExtractService userExtractService;

	private final ShsyTaskJob shsyTaskJob;



//	/**
//	 * 商城首页
//	 */
//	@GetMapping("/job")
//	@ApiOperationSupport(order = 1)
//	@ApiOperation(value = "商城任务")
//	public R index1(String job) {
//		switch(job){
//			case "testJobHandler":  shsyTaskJob.testJobHandler(); break;
//			case "grantBonusJobHandler":
//				try {
//					shsyTaskJob.grantBonusJobHandler();
//				} catch (Exception exception) {
//					exception.printStackTrace();
//				}
//				break;
//		}
//		return R.success("成功:"+job);
//	}


	/**
	 * 商城首页
	 */
	@GetMapping("/index")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "商城首页")
	public R index(String tenantId) {
		if (Func.isNull(tenantId)) {
			tenantId = "000000";
		}
		JSONArray canvas = JSONArray.parseArray(ParamCache.getValue(tenantId + ".store.canvas"));
		for (int i = 0; i < canvas.size(); i++) {
			JSONObject object = canvas.getJSONObject(i);
			if ("hotCommodity".equals(object.get("type"))) {
				List<StoreProduct> list = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
					.eq(StoreProduct::getTenantId, tenantId)//租户
					.eq(StoreProduct::getIsHot, 1)//热卖商品
					.eq(StoreProduct::getIsDeleted, 0)//未删除
					.eq(StoreProduct::getIsIntegral, 0)//非积分
					.eq(StoreProduct::getStatus, 1)//已上架
					.orderByDesc(StoreProduct::getSort)
					.last("limit 0,6")
				);
				object.put("componentContent", list);
			}
			if ("promotionGood".equals(object.get("type"))) {
				List<StoreProduct> list = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
					.eq(StoreProduct::getTenantId, tenantId)//租户
					.eq(StoreProduct::getIsBest, 1)//是否精品
					.eq(StoreProduct::getIsDeleted, 0)//未删除
					.eq(StoreProduct::getIsIntegral, 0)//非积分
					.eq(StoreProduct::getStatus, 1)//已上架
					.orderByDesc(StoreProduct::getSort)
					.last("limit 0,6")
				);
				object.put("componentContent", list);
			}
		}
		return R.data(canvas);
	}

	/**
	 * 商城首页
	 */
	@GetMapping("/mnIndex")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "商城管理端首页")
	public R mnIndex(String tenantId) {
		if (Func.isNull(tenantId)) {
			tenantId = "000000";
		}
		JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();
		object.put("title", "会员数量");
		object.put("count", userService.count());
		object.put("icon", "el-icon-school");
		array.add(object);
		object = new JSONObject();
		object.put("title", "订单总数");
		object.put("count", userOrderService.count());
		object.put("icon", "el-icon-house");
		array.add(object);
		object = new JSONObject();
		object.put("title", "订单总额");
		object.put("count", userOrderService.sumPayPrice());
		object.put("icon", "el-icon-user");
		array.add(object);
		object = new JSONObject();
		object.put("title", "红包总数");
		object.put("count", userBonusService.count());
		object.put("icon", "el-icon-help");
		array.add(object);
		object = new JSONObject();
		object.put("title", "红包总额");
		object.put("count", userBonusService.sumBonus());
		object.put("icon", "el-icon-suitcase");
		array.add(object);
		object = new JSONObject();
		object.put("title", "提现总额");
		object.put("count", userExtractService.sumAmount());
		object.put("icon", "el-icon-timer");
		array.add(object);
		return R.data(array);
	}

	/**
	 * 商城版本
	 */
	@GetMapping("/version")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "商城版本")
	public R version(String tenantId) {
		if (Func.isNull(tenantId)) {
			tenantId = "000000";
		}
		return R.data(JSONArray.parseArray(ParamCache.getValue(tenantId + ".app.version")));
	}

	/**
	 * 红包日历
	 */
	@GetMapping("/bonusCalendar/info")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "红包日历-列表")
	public R bonusCalendar() {//String tenantId
//		if(Func.isNull(tenantId)){
//			tenantId = "000000";
//		}
		String tenantId = "000000";
		return R.data(JSONArray.parseArray(ParamCache.getValue(tenantId + ".bonus.calendar")));
	}

	/**
	 * 红包日历
	 */
	@PostMapping("/bonusCalendar/update")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "红包日历-更新")
	public R bonusCalendarUpdate(@ApiIgnore @RequestBody JSONArray array) {
		String tenantId = "000000";
//		if(!ZnApiUtils.isJsonArray(array.replaceAll("\"",""))){throw new ServiceException("请传JsonArray格式数据!");}
		paramService.update(Wrappers.<Param>update().lambda().set(Param::getParamValue, array.toJSONString()).eq(Param::getParamKey, tenantId + ".bonus.calendar"));
		CacheUtil.clear(PARAM_CACHE);
		CacheUtil.clear(PARAM_CACHE, Boolean.FALSE);
		if (!Func.isNull(array) && array.size() > 0) {
			for (int i = 0; i < array.size(); i++) {
				JSONObject jsonObject = array.getJSONObject(i);
				StoreCalendar storeCalendar = new StoreCalendar();
//				List<StoreCalendar> list = storeCalendarService.list(Wrappers.<StoreCalendar>lambdaQuery()
//					.eq(StoreCalendar::getParam0, jsonObject.getDate("date"))
//				);
//				if (list!=null && list.size() > 0) {
//					storeCalendar.setId(list.get(0).getId());
//				}
				storeCalendar.setParam0(jsonObject.getDate("date"));
				storeCalendar.setParam1(jsonObject.getJSONObject("rule").getBigDecimal("le"));
				storeCalendar.setParam2(jsonObject.getJSONObject("rule").getBigDecimal("ge"));
				storeCalendar.setParam3(jsonObject.getJSONObject("rule").getBigDecimal("two"));
				storeCalendarService.saveOrUpdate(storeCalendar);
			}
		}
		return R.status(true);
	}

	@GetMapping("bootScreen")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "APP启动界面")
	public R bootScreen(String tenantId) {
		if (Func.isNull(tenantId)) {
			tenantId = "000000";
		}
		return R.data(JSONArray.parseArray(ParamCache.getValue(tenantId + ".boot.screen")));
	}
}
